﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using SyncCommon;
using System.Web;

namespace SyncWebSite
{
    public class SyncGanJi : SyncHouseBase
    {

        private Dictionary<string, string> loginCookies = new Dictionary<string, string>();
        private List<string> retImages = new List<string>();
        private List<string> retthumbImages = new List<string>();
        private string CityShort;
        #region SyncHouseBase

        public SyncGanJi(string username, string password)
            :base(username,password)
        {
            
        }

        public override bool CheckLogin()
        {
            WebRequest request = new WebRequest("http://www.ganji.com/user/login.php");
            request.Cookies = loginCookies;
            string ret = request.GetResouceStr();
            request = new WebRequest("http://www.ganji.com/user/login.php", FormType.FormUrlEncode);
            request.Cookies = loginCookies;
            if (ret.Contains("nocache="))
            {
                string code = PrcoessValidationCode("http://www.ganji.com/common/checkcode.php?w=150&h=60");
                request.AddContent("checkcode", code);
            }

            request.AddStringCookies("__utmc=32156897; _gl_tracker=%7B%22ca_source%22%3A%22www.baidu.com%22%2C%22ca_name%22%3A%22se%22%2C%22ca_kw%22%3A%22%25E8%25B5%25B6%25E9%259B%2586%7Cutf8%22%2C%22ca_id%22%3A%22%22%2C%22sid%22%3A68706960406%7D; Hm_lpvt_86999365b2cd5912e51ace0f598476cb=1346065973812; login_num=0; GANJISESSID=3bde86b6faf67806df994ebb129c8fce; citydomain=sh; __utma=32156897.554565538.1346065507.1346065507.1346065507.1; __utmb=32156897.16.10.1346065507; __utmz=32156897.1346065507.1.1.utmcsr=baidu|utmccn=(organic)|utmcmd=organic|utmctr=%E8%B5%B6%E9%9B%86;");
            request.AddContent("expireDays", "90");
            request.AddContent("password", Password);
            request.AddContent("source", "passport");
            request.AddContent("setcookie", "90");
            request.AddContent("username", UserName);
            string status = request.SendWaitString();
            if (status.Contains("login_success"))
            {
                return true;
            }
            return false;
        }

        public override bool AddSaleHouse(HouseInfo info, ref string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);

            string error = "";
            try
            {
                if (!CheckLogin())
                {
                    error = "登录失败";
                    //UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                }
                else
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, true, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetCityShort(info.City);
                    SyncImages(info);

                    WebRequest request = new WebRequest("http://www.ganji.com/pub/pub.php?cid=7&mcid=21&act=pub&method=submit", FormType.MultiPart);
                    request.Cookies = loginCookies;
                    string ret = request.GetResouceStr();
                    request = new WebRequest("http://www.ganji.com/pub/pub.php?cid=7&mcid=21&act=pub&method=submit", FormType.MultiPart);
                    request.Cookies = loginCookies;
                    if (ret.Contains("验证码</th>"))
                    {
                        string code = PrcoessValidationCode("http://www.ganji.com/common/checkcode.php?w=150&h=60");
                        request.AddContent("checkcode", code);

                        //WebRequest newRequest = new WebRequest("http://www.ganji.com/common/ajax/check_code.php", FormType.FormUrlEncode);
                        //newRequest.Cookies = loginCookies;
                        //newRequest.AddContent("checkcode", code);
                        //if (!newRequest.GetResouceStr().Contains("true"))
                        //{
                        //    error = "验证码输入错误";
                        //    UpdateCurrentStatus(StandardProgress.Failed, error);
                        //    return false;
                        //}
                    }

                    request.Cookies = loginCookies;

                    request.AddContent("title", info.Title);

                    //获取小区相信信息
                    GetEstateDetail(request, info, ret);

                    request.AddContent("huxing_shi", info.Room);
                    request.AddContent("huxing_ting", info.Hall);
                    request.AddContent("huxing_wei", info.WashRoom);

                    request.AddContent("agent", "1");
                    request.AddContent("ceng", info.CurrentFloor);
                    request.AddContent("ceng_total", info.Floors);

                    request.AddContent("chaoxiang", GetToward(info.Toward));
                    request.AddContent("fang_xing", GetHouseType(info.HouseType));
                    request.AddContent("zhuangxiu", GetDecoration(info.Decoration));

                    request.AddContent("niandai", info.Age);
                    request.AddContent("area", info.Area);
                    request.AddContent("price", info.Price);
                    request.AddContent("description", info.Description);

                    request.AddContent("images", GetImages());
                    request.AddContent("phone", info.Mobile);
                    request.AddContent("person", info.Name);
                    if (info.Name.Length > 6 || info.Name.Length < 2)
                    {
                        error = "发布者姓名必须2-6个字";
                        goto erroHanlder;

                    }
                    request.AddContent("sticky", "0");
                    UpdateCurrentStatus(StandardProgress.PosData);
                    string status = request.SendWaitString();
                    if (status.Contains("您已发布过类似信息") && status.Contains("老信息将被删除"))
                    {
                        error = "您已发布过类似信息,请修改房源信息后再试";
                        UpdateCurrentStatus(StandardProgress.Failed, error);

                        return false;
                    }

                    if (status.Contains("需要您的进一步确认") || status.Contains("您已发布过类似信息"))
                    {
                        error = "已有相似房源添加";
                        UpdateCurrentStatus(StandardProgress.Failed, error);

                        return false;
                    }
                    if (status.Contains("发布成功"))
                    {
                        if (status.Contains("15分钟后将出现在网页上"))
                        {
                            error = "15分钟后将出现在网页上！";
                        }
                        string targeUrl = "";
                        targetID = GetTargetID(info.Title, ref targeUrl);
                        UpdateCurrentStatus(StandardProgress.Sucess, error+GetImageError(info), targetID, targeUrl);
                        return true;
                    }
                    if (status.Contains("displayError("))
                    {
                        Regex reg = new Regex("(?<=displayError\\(\").*?(?=\"\\))");
                        Match ma = reg.Match(status);
                        if (ma.Success)
                        {
                            error = ma.Value;
                        }
                        else
                        {
                            error = "提交信息不符合赶集网标准";
                        }
                        UpdateCurrentStatus(StandardProgress.Failed, error);
                        return false;
                    }
                    if (status.Contains("立即发布"))
                    {
                        error = "提交信息不符合赶集网标准";
                        UpdateCurrentStatus(StandardProgress.Failed, error);
                        return false;
                    }
                    error = "发布失败";
                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("赶集信息提交", exp);
                error = exp.Message;
            }
        erroHanlder:
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;

        }
        public override bool AddRentHouse(HouseInfo info, ref string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
         
            string error = "";
            try
            {
                if (!CheckLogin())
                {
                    error = "登录失败";
                    //UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                }
                else
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, false, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetCityShort(info.City);
                    SyncImages(info);
                    WebRequest request = new WebRequest("http://www.ganji.com/pub/pub.php?cid=7&mcid=20&act=pub&method=submit", FormType.MultiPart);
                    request.Cookies = loginCookies;
                    string ret = request.GetResouceStr();
                    request = new WebRequest("http://www.ganji.com/pub/pub.php?cid=7&mcid=20&act=pub&method=submit", FormType.MultiPart);
                    request.Cookies = loginCookies;
                    if (ret.Contains("验证码</th>"))
                    {
                        string code = PrcoessValidationCode("http://www.ganji.com/common/checkcode.php?w=150&h=60");
                        request.AddContent("checkcode", code);

                        //WebRequest newRequest = new WebRequest("http://www.ganji.com/common/ajax/check_code.php", FormType.FormUrlEncode);
                        //newRequest.Cookies = loginCookies;
                        //newRequest.AddContent("checkcode", code);
                        //if (!newRequest.GetResouceStr().Contains("true"))
                        //{
                        //    error = "验证码输入错误";
                        //    UpdateCurrentStatus(StandardProgress.Failed, error);
                        //    return false;
                        //}
                    }

                    request.Cookies = loginCookies;

                    request.AddContent("title", info.Title);

                    //获取小区相信信息
                    GetEstateDetail(request, info, ret);

                    #region Rent Related Information
                    request.AddContent("pay_type_int", GetPayment(info));
                    request.AddContent("share_type_list", "1");
                    request.AddContent("share_mode", "1");
                    request.AddContent("house_type", "2");
                    request.AddContent("rent_mode", GetRentType(info));
                    request.AddContent("price", info.MonthPrice);
                    #endregion

                    request.AddContent("huxing_shi", info.Room);
                    request.AddContent("huxing_ting", info.Hall);
                    request.AddContent("huxing_wei", info.WashRoom);

                    request.AddContent("agent", "1");
                    request.AddContent("ceng", info.CurrentFloor);
                    request.AddContent("ceng_total", info.Floors);

                    request.AddContent("chaoxiang", GetToward(info.Toward));
                    request.AddContent("fang_xing", GetHouseType(info.HouseType));
                    request.AddContent("zhuangxiu", GetDecoration(info.Decoration));

                    request.AddContent("niandai", info.Age);
                    request.AddContent("area", info.Area);

                    request.AddContent("description", info.Description);

                    request.AddContent("images", GetImages());
                    request.AddContent("phone", info.Mobile);
                    request.AddContent("person", info.Name);
                    if (info.Name.Length > 6 || info.Name.Length < 2)
                    {
                        error = "发布者姓名必须2-6个字";
                        goto erroHanlder;

                    }
                    request.AddContent("sticky", "0");
                    UpdateCurrentStatus(StandardProgress.PosData);
                    string status = request.SendWaitString();
                    if (status.Contains("您已发布过类似信息") && status.Contains("老信息将被删除"))
                    {
                        error = "您已发布过类似信息,请修改房源信息后再试";
                        UpdateCurrentStatus(StandardProgress.Failed, error);

                        return false;
                    }

                    if (status.Contains("需要您的进一步确认") || status.Contains("您已发布过类似信息"))
                    {
                        error = "已有相似房源添加";
                        UpdateCurrentStatus(StandardProgress.Failed, error);

                        return false;
                    }
                    if (status.Contains("发布成功"))
                    {
                        if (status.Contains("15分钟后将出现在网页上"))
                        {
                            error = "15分钟后将出现在网页上！";
                        }
                        string targeUrl = "";
                        targetID = GetTargetID(info.Title, ref targeUrl);
                        UpdateCurrentStatus(StandardProgress.Sucess, error + GetImageError(info), targetID, targeUrl);
                        return true;
                    }
                    if (status.Contains("displayError("))
                    {
                        Regex reg = new Regex("(?<=displayError\\(\").*?(?=\"\\))");
                        Match ma = reg.Match(status);
                        if (ma.Success)
                        {
                            error = ma.Value;
                        }
                        else
                        {
                            error = "提交信息不符合赶集网标准";
                        }
                        UpdateCurrentStatus(StandardProgress.Failed, error);
                        return false;
                    }
                    if (status.Contains("立即发布"))
                    {
                        error = "提交信息不符合赶集网标准";
                        UpdateCurrentStatus(StandardProgress.Failed, error);
                        return false;
                    }
                    error = "发布失败";

                }

            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("赶集信息提交", exp);
                error = exp.Message;
            }
        erroHanlder:
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }
        public override bool DeleteRentHouse(HouseInfo info, string targetID)
        {
            return InnerDelete(info, targetID, false);
        }
        public override bool DeleteSaleHouse(HouseInfo info, string targetID)
        {
            return InnerDelete(info, targetID,true);
        }

        public bool InnerDelete(HouseInfo info, string targetID, bool isSale)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            try
            {
                if (CheckLogin())
                {
                    string url = "http://www.ganji.com/vip/ajax/rm_post.php";
                    WebRequest request = new WebRequest(url, FormType.FormUrlEncode);
                    request.Cookies = loginCookies;
                    string id = "";
                    //if (isSale)
                    //{
                    //    id = targetID.Split(',')[0] + ",26,21,0";
                    //}
                    //else
                    //{
                    //    id = targetID.Split(',')[0] + ",26,20,0";
                    //}
                    id = targetID;
                    request.AddContent("one", id ?? "");
                    request.AddContent("permanently", "0");
                    request.AddContent("_html", "");
                    request.AddContent("_msg", "");
                    UpdateCurrentStatus(StandardProgress.PosData);
                    string ret = request.SendWaitString();
                    if (ret.Contains("true"))
                    {
                        UpdateCurrentStatus(StandardProgress.Sucess);
                        return true;
                    }
                    else
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, "删除房源失败");
                        LogCenter.LogMessage("删除失败(赶集),Target:" + targetID + "返回值" + ret);
                        return false;
                    }
                }
                else
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                    return false;
                }
            }
            catch (System.Net.WebException exp)
            {
                UpdateCurrentStatus(StandardProgress.Failed, WebError);
                return false;
            }
        }

      
   
        #endregion

        #region HelpFunction
        public void SyncImages(HouseInfo info)
        {
            retImages.Clear();
            retthumbImages.Clear();
            errorImage = 0;
            if (info.Images != null)
            {
                foreach (string url in info.Images)
                {
                    try
                    {
                        WebRequest request = new WebRequest(url);
                        Stream stream = request.GetResouce();
                        string name = url.Substring(url.LastIndexOf('/') + 1);
                        request = new WebRequest("http://image.ganji.com/upload.php", FormType.MultiPart);
                        request.AddContent("resizeWidth", "600");
                        request.AddContent("resizeHeight", "450");

                        request.AddContent("thumbWidth", "90");
                        request.AddContent("thumbHeight", "75");
                        request.AddContent("resizeImage", "true");
                        request.AddContent("uploadDir", "tmp");
                        request.AddFile(name, stream);
                        string k = request.SendWaitString();
                        if (k.Contains("\"error\":0"))
                        {
                            Regex reg = new Regex("(?<=url\":\").*?(?=\")");
                            Match ma = reg.Match(k);
                            if (ma.Success)
                            {
                                retImages.Add(ma.Value.Replace("\\", ""));
                            }
                            reg = new Regex("(?<=thumbUrl\":\").*?(?=\")");
                            ma = reg.Match(k);
                            if (ma.Success)
                            {
                                this.retthumbImages.Add(ma.Value.Replace("\\", ""));
                            }
                        }
                        else
                        {
                            errorImage++;
                        }

                    }
                    catch
                    {
                        errorImage++;
                    }
                    //"url":"gjfs01\/M00\/90\/ED\/wKhxwVA7WgbEh,MeAACrMximQrI529.jpg"
                    //{"error":0,"text":"\u4e0a\u4f20\u6210\u529f","info":[{"name":"n_20893892055313.jpg","type":"image\/pjpeg","tmp_name":"\/tmp\/phpsI06Kn","error":"0","size":"36754","field_name":"Filedata","is_image":"1","width":"600","height":"450","image_type":"jpg","path":"\/data\/upload_tmp\/20120827\/1929\/","file":"\/data\/upload_tmp\/20120827\/1929\/1346066950-3060.raw.jpg","formatSize":"41.33 kb","newName":"1346066950-3060.raw.jpg","url":"gjfs01\/M00\/90\/ED\/wKhxwVA7WgbEh,MeAACrMximQrI529.jpg","thumbUrl":"gjfs01\/M00\/90\/ED\/wKhxwVA7WgbEh,MeAACrMximQrI529_90-75c_6-0.jpg","image_info":[600,450]}],"params":{"uploadRootDir":"\/data","uploadDir":"tmp","uploadAll":true,"maxSize":"10485759","type":"gif,jpg,jpeg,png,bmp","thumbWidth":"90","thumbHeight":"75","useDomain":false,"minWidth":"0","minHeight":"0","resizeImage":true,"resizeWidth":"600","resizeHeight":"450","_guid":"guid_26_13460669437650_5805999141754131","MAX_FILE_SIZE":"10485759","createThumb":false,"resizeCutEnable":false,"thumbCutEnable":true}}
                }
            }
        }

        private string GetPayment(HouseInfo info)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            //目标 1:押一付三 2:其他 3:押一付一 4:押一付二 5:押二付一 9:押二付三 6:半年付不押 7:年付不押 8:押一付半年 10:押一付年
            switch (info.PayType)
            { 
                case "1":
                    return "3";
                case "2":
                    return "4";
                case "3":
                    return "1";
                case "4":
                    return "8";
                default:
                    return "2";
            }
        }

        private string GetPayment_Description(HouseInfo info)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            //目标 1:押一付三 2:其他 3:押一付一 4:押一付二 5:押二付一 9:押二付三 6:半年付不押 7:年付不押 8:押一付半年 10:押一付年
            switch (info.PayType)
            {
                case "1":
                    return "押一付一";
                case "2":
                    return "押一付二";
                case "3":
                    return "押一付三";
                case "4":
                    return "押一付半年";
                default:
                    return "其他";
            }
        }


        private string GetRentType(HouseInfo info)
        {
            switch (info.HireType)
            { 
                case "0":
                    return "2";
                case "1":
                    return "2";
                default:
                    return "1";
            }
        }

        private string PrcoessValidationCode(string url)
        {
            string loginCodeUrl = url;
            WebRequest request = new WebRequest(url);
            request.Cookies = loginCookies;
            //验证码处理代码待加
            return GetValidationCode(request.GetResouce());
        }

        public string GetTargetID(string title,ref string targetUrl)
        {
            string url = "http://www.ganji.com/vip/my_post_list.php";
            WebRequest request = new WebRequest(url);
            request.ReturnEncoding = Encoding.UTF8;
            request.Cookies = loginCookies;
            string ret = request.GetResouceStr();
            string targetID = "";
            MatchCollection matchs = null;
            if (!string.IsNullOrEmpty(ret))
            {
                //修改</a> | <a title="删除该帖" href="#" class="ev_rm_post" tip="a" pid="1863543,13,21,0" permanently="0">删除</a> | <a title="联系客服" href="#" url="/vip/my_post_question_list.php?post_id=1863543&city=100&category=2&major_category=5&deleted_reason=&tiwen_type=auditpost&db_post_url=http%3A%2F%2Fsh.ganji.com%2Ffang5%2F338771474x.htm" class="ev_show_tiwen">联系客服</a>                </span>

                Regex regex = new Regex("修改[\\S\\s]*?<a[\\S\\s]*?pid=[\"'](?<hid>[\\S\\s]*?)[\"'] permanently[\\S\\s]*?>删除[\\S\\s]*?<a href[\\S\\s]*?>(?<title>[\\S\\s]*?)</a>[\\S\\s]*?联系客服[\\S\\s]*?<a href[\\S\\s]*?>(?<type>[\\S\\s]*?)</a>");
                matchs = regex.Matches(ret);
                if (matchs != null)
                {
                    foreach (Match match in matchs)
                    {
                        if ((match.Groups["title"].Value ?? "") == title)
                        {
                            targetID = match.Groups["hid"].Value ?? "";
                            break;
                        }
                    }
                }
            }
            //<a href="http://sh.ganji.com/fang5/338771474x.htm" target="_blank">张江玉兰香苑2房出售</a>

            Regex reg = new Regex("<a href=\"(?<url>.*?)\" target=\"_blank\">(?<title>.*?)</a>");
            matchs = reg.Matches(ret);
            if (matchs != null)
            {
                foreach (Match match in matchs)
                {
                    if ((match.Groups["title"].Value ?? "") == title)
                    {
                        targetUrl = match.Groups["url"].Value ?? "";
                        break;
                    }
                }
            }
            return targetID;
        }

        private void GetEstateDetail(WebRequest subRequest, HouseInfo info, string htm)
        {

            bool findMatch = false;
            string url = "http://www.ganji.com/ajax.php?module=xiaoqu_name_autocomplete&key=" + HttpUtility.UrlEncode(info.Estate) + "&city=" + CityShort;
            WebRequest request = new WebRequest(url);
            request.SetHeaderValue("Referer", "http://www.ganji.com/pub/pub.php?act=pub&method=load&cid=7&mcid=21&domain=" + CityShort);
            request.SetHeaderValue("x-requested-with", "XMLHttpRequest");
            request.SetHeaderValue("Accept", "application/json, text/javascript, */*");
            string ret = request.GetResouceStr();
            if (string.IsNullOrEmpty(ret))
            {
                //LogCenter.LogMessage("无法匹配小区(赶集),小区:" + info.Estate + "，城市:" + info.City);
            }
            else
            {
                ret = HtmlHelper.RemoveHtmlCode(HtmlHelper.HexDecode(ret));
                string pattern = @"[""|']x_id[""|']:[""|'](?<id>[\d\s]*?)[""|'],[""|']name[""|']:[""|'](?<name>[\S\s]*?)[""|'],[""|']n[""|']:[""|'](?<qkId>[\d\s]*?)[""|'],[\S\s]*?[""|']d_n[""|']:[""|'](?<qkName>[\S\s]*?)[""|'],[""|']s_n[""|']:[""|'](?<qkName>[\S\s]*?)[""|'],[\S\s]*?[""|']address[""|']:[""|'](?<address>[\S\s]*?)[""|'],[""|']latlng[""|']:[""|'](?<latlng>[\S\s]*?)[""|']";
                Regex regex = new Regex(pattern);
                MatchCollection matchs = null;

                Match ma = regex.Match(ret);

                if (ma.Success)
                {
                    string esateID = (ma.Groups["id"].Value ?? "").Trim();
                    string esateName = (ma.Groups["name"].Value ?? "").Trim();
                    if (!string.IsNullOrEmpty(esateID))
                    {
                        url = "http://www.ganji.com/ajax.php?module=XiaoquGetInfoById";
                        WebRequest XiaoQuRequest = new WebRequest(url, FormType.FormUrlEncode);
                        XiaoQuRequest.Cookies = loginCookies;
                        XiaoQuRequest.AddContent("name", esateID);
                        XiaoQuRequest.AddContent("xiaoqu", esateName);
                        ret = XiaoQuRequest.SendWaitString();
                        ret = HtmlHelper.RemoveHtmlCode(HtmlHelper.HexDecode(ret));
                        pattern = "[\"']id[\"']:[\"'](?<id>[\\d\\s]*?)[\"'],[\"']name[\"']:[\"'](?<name>[\\S\\s]*?)[\"'],[\\S\\s]*?[\"']pinyin[\"']:[\"'](?<pinyin>[\\S\\s]*?)[\"'],[\"']latlng[\"']:[\"'](?<latlng>[\\S\\s]*?)[\"'],[\\S\\s]*?[\"']address[\"']:[\"'](?<address>[\\S\\s]*?)[\"'],[\\S\\s]*?district_info[\\S\\s]*?,[\"']id[\"']:[\"'](?<qkId>[\\d\\s]*?)[\"'],[\\S\\s]*?[\"']name[\"']:[\"'](?<qkName>[\\S\\s]*?)[\"'],([\\S\\s]*?street_info[\\S\\s]*?[\"']id[\"']:[\"'](?<sqId>[\\d\\s]*?)[\"'],[\\S\\s]*?[\"']name[\"']:[\"'](?<sqName>[\\S\\s]*?)[\"'],)?";
                        regex = new Regex(pattern);
                        ma = regex.Match(ret);
                        if (ma.Success)
                        {
                            findMatch = true;
                            string str3 = "";
                            string fieldValue = "";
                            subRequest.AddContent("xiaoqu", info.Estate);
                            subRequest.AddContent("xiaoqu_address", info.LocalAddress ?? "");
                            subRequest.AddContent("pinyin", ma.Groups["pinyin"].Value.Trim() ?? "");
                            subRequest.AddContent("latlng", ma.Groups["latlng"].Value.Trim() ?? "");
                            subRequest.AddContent("district_id", ma.Groups["qkId"].Value.Trim() ?? "");
                            subRequest.AddContent("street_id", ma.Groups["sqId"].Value.Trim() ?? "");
                        }
                    }
                }
            }
            if (!findMatch)
            {
                subRequest.AddContent("xiaoqu", info.Estate);
                subRequest.AddContent("xiaoqu_address", info.LocalAddress ?? "");
                subRequest.AddContent("pinyin", "");
                subRequest.AddContent("latlng", "");

                Regex distReg = new Regex(@"<option value=""(?<districtID>\d*)""\s*?script_index='(?<index>\d*)'>"+info.LocalDistrict+"</option>");
                ///<option value="196"  script_index='10'>普陀</option>
                Match ma = distReg.Match(htm);
                if (ma.Success)
                {
                    subRequest.AddContent("district_id", ma.Groups["districtID"].Value);
                    WebRequest streetRequest = new WebRequest("http://www.ganji.com/ajax.php?module=streetOptions", FormType.FormUrlEncode);
                    streetRequest.Cookies = loginCookies;
                    streetRequest.AddContent("domain", CityShort);
                    streetRequest.AddContent("district_id", ma.Groups["districtID"].Value);
                    streetRequest.AddContent("with_all_option", "1");
                    string retStreet = streetRequest.SendWaitString();
                    retStreet = HtmlHelper.RemoveHtmlCode(HtmlHelper.HexDecode(retStreet));

                    //"7227","\u5149\u65b0",false,"16"
                    Regex streetReg = new Regex(@"\[""(?<streetID>\d*)"",""" + info.LocalDiduan + @""",false,""\d*""\]");
                    Match strMa = streetReg.Match(retStreet);
                    if (strMa.Success)
                    {
                        subRequest.AddContent("street_id", strMa.Groups["streetID"].Value);
                    }
                    else
                    {
                        subRequest.AddContent("street_id", "-1");
                    }
                }
                else
                {
                    throw new UnFindDistrictException(info.LocalDistrict);
                }

            }
        }

        public void GetCityShort(string CityName)
        {
            if (CityName == "上海")
            {
                CityShort = "sh";
            }
        }
        public string GetDistrictID(string district)
        {
            if (district == "浦东")
                return "203";
            return "203";
        }

        public string GetDiduan(string diduan)
        {
            if (diduan == "张江")
            {
                return "5955";
            }
            return "5955";
        }

        public string GetDecoration(string dec)
        {
            //当前 1:毛胚 2:简装 3:精装 4:豪装
            //目标 1:豪华装修 2:精装修 3:中等装修 4:简单装修 5：毛坯
            switch (dec)
            {
                case "1":
                    return "5";
                case "2":
                    return "4";
                case "3":
                    return "2";
                case "4":
                    return "1";
                default:
                    return "2";
            }
        }
        public string GetDecoration_Description(string dec)
        {
            //当前 1:毛胚 2:简装 3:精装 4:豪装
            //目标 1:豪华装修 2:精装修 3:中等装修 4:简单装修 5：毛坯
            switch (dec)
            {
                case "1":
                    return "毛坯";
                case "2":
                    return "简单装修";
                case "3":
                    return "精装修";
                case "4":
                    return "豪华装修";
                default:
                    return "精装修";
            }
        }
        public string GetHouseType(string type)
        { 
            //平房=1,普通住宅=2,商住两用=3,公寓=4,别墅=5,其他=6
            switch (type)
            {
                case "1":
                    return "2";//平房/四合院
                case "2":
                    return "3";//普通住宅
                case "4":
                    return "4";//公寓
                case "3":
                    return "5";//商住楼
                case "5":
                    return "7";//别墅
                case "6":
                    return "8";//文字 - 其他
            }
            return "3";
        }
        public string GetHouseType_Description(string type)
        {
            //平房=1,普通住宅=2,商住两用=3,公寓=4,别墅=5,其他=6
            switch (type)
            {
                case "1":
                    return "平房";//平房/四合院
                case "2":
                    return "普通住宅";//普通住宅
                case "4":
                    return "公寓";//公寓
                case "3":
                    return "商住楼";//商住楼
                case "5":
                    return "别墅";//别墅
                case "6":
                    return "其他";//文字 - 其他
            }
            return "商住楼";
        }
        public string GetToward(string toward)
        {
            //当前 1=东 2=南 3=西 4=北 5=南北 6=东西 7=东南 8=西南 9=东北 10=西北 11=不知道朝向
            //目标 1=东 2=南 3=西 4=北 6=南北 5=东西 7=东南 9=西南 8=东北 10=西北 
            if (toward == "5")
            {
                return "6";
            }   
            if (toward == "6")
            {
                return "5";
            }
            if (toward == "9")
            {
                return "8";
            }
            if (toward == "11")
            {
                return "2";
            }
            return toward;
        }
        public string GetToward_Description(string toward)
        {
            //当前 1=东 2=南 3=西 4=北 5=南北 6=东西 7=东南 8=西南 9=东北 10=西北 11=不知道朝向
            //目标 1=东 2=南 3=西 4=北 6=南北 5=东西 7=东南 9=西南 8=东北 10=西北 
            if (toward == "1")
            {
                return "东";
            }
            if (toward == "2")
            {
                return "南";
            }
            if (toward == "3")
            {
                return "西";
            }
            if (toward == "4")
            {
                return "北";
            }
            
            if (toward == "5")
            {
                return "南北";
            }
            if (toward == "6")
            {
                return "东西";
            }
            if (toward == "7")
            {
                return "东南";
            }
            if (toward == "8")
            {
                return "西南";
            }

            if (toward == "9")
            {
                return "东北";
            }

            if (toward == "10")
            {
                return "西北";
            }
            if (toward == "11")
            {
                return "东";
            }
            return "东";
        }
        public string GetImages()
        { 
            StringBuilder builder = new StringBuilder();
            builder.Append("[[");
            for(int i=0;i<retImages.Count;i++)
            {
                if (i == 0)
                {
                    builder.Append(string.Format("{{\"image\":\"{0}\",\"thumb_image\":\"{1}\",\"width\":\"600\",\"height\":\"450\",\"id\":\"SWFUpload_0_{2}\",\"is_new\":true}}", retImages[i], retthumbImages[i], i.ToString()));
                }
                else
                {
                    builder.Append(string.Format(",{{\"image\":\"{0}\",\"thumb_image\":\"{1}\",\"width\":\"600\",\"height\":\"450\",\"id\":\"SWFUpload_0_{2}\",\"is_new\":true}}", retImages[i], retthumbImages[i], i.ToString()));
                }
                
            }
            builder.Append("],[]]");
            string temp = builder.ToString();
            return temp;
        }
        #endregion

        public override bool CheckTitle(HouseInfo infor, bool isSale, ref string errorInfor)
        {
            if (string.IsNullOrEmpty(infor.Title))
            {
                errorInfor = "标题不能为空";
                return false;
            }

            if (infor.Title.Length < 6
                || infor.Title.Length > 30)
            {
                errorInfor = "标题必须6-30字，不能包括电话等信息";
                return false;
            }

            return true;
        }


        #region 编辑功能
        public override bool OpenEidt(WebBrowserOp op, HouseInfo info)
        {
            try
            {
                if (CheckLogin())
                {
                    if (info.TradeType == TradeType.Sale)
                    {
                        string post = "http://www.ganji.com/pub/pub.php?act=pub&method=load&cid=7&mcid=21&domain=sh";
                        foreach (KeyValuePair<string, string> k in loginCookies)
                        {
                            WebBrowserOp.InternetSetCookie(post, k.Key, k.Value);
                        }
                        op.HouseInformation = info;
                        op.Navigate(post);
                        op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Sale_Completed);
                    }
                    else
                    {
                        string post = "http://www.ganji.com/pub/pub.php?act=pub&method=load&cid=7&mcid=20&domain=sh";
                        foreach (KeyValuePair<string, string> k in loginCookies)
                        {
                            WebBrowserOp.InternetSetCookie(post, k.Key, k.Value);
                        }
                        op.HouseInformation = info;
                        op.Navigate(post);
                        op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Rent_Completed);
                    }

                }
                else
                {
                    return false;
                }
            }
            catch
            {
                op.Navigate("http://www.ganji.com");
            }
            return true;
        }
        void op_Sale_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserOp cl = sender as WebBrowserOp;
            HouseInfo info = cl.HouseInformation;
            cl.SetValueByID("title", info.Title);

            cl.SetValueByID("id_xiaoqu", info.Estate);
            cl.SetValueByID("id_district_id", GetDistrictID(info.LocalDistrict));


            cl.SetValueByID("id_xiaoqu_address", info.LocalAddress);

            cl.CheckByName_Value("agent","1",true);

            cl.SetValueByName("huxing_shi", info.Room);
            cl.SetValueByName("huxing_ting", info.Hall);
            cl.SetValueByName("huxing_wei", info.WashRoom);

            cl.SetValueByName("ceng", info.CurrentFloor);
            cl.SetValueByName("ceng_total", info.Floors);

            cl.SetValueByName("chaoxiang", GetToward(info.Toward));
            cl.SetValueByName_BigBrother("chaoxiang", GetToward_Description(info.Toward));
            cl.SetValueByName("fang_xing", GetHouseType(info.HouseType));
            cl.SetValueByName_BigBrother("fang_xing", GetHouseType_Description(info.HouseType));

            cl.SetValueByName("zhuangxiu", GetDecoration(info.Decoration));
            cl.SetValueByName_BigBrother("zhuangxiu", GetDecoration_Description(info.HouseType));

            cl.SelectByName_Value("direction", GetToward(info.Toward));

            cl.SetValueByName("niandai", info.Age);
            cl.SetValueByName("area", info.Area);
            cl.SetValueByName("price", info.Price);
            cl.SetValueByID("id_description", info.Description);


            cl.SetValueByName("phone", info.Mobile);
            cl.SetValueByName("person", info.Name);

        }
        void op_Rent_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserOp cl = sender as WebBrowserOp;
            HouseInfo info = cl.HouseInformation;
            cl.SetValueByID("title", info.Title);

            cl.SetValueByID("id_xiaoqu", info.Estate);
            cl.SetValueByID("id_district_id", GetDistrictID(info.LocalDistrict));


            cl.SetValueByID("id_xiaoqu_address", info.LocalAddress);

            cl.CheckByName_Value("agent", "1", true);

            cl.SetValueByName("huxing_shi", info.Room);
            cl.SetValueByName("huxing_ting", info.Hall);
            cl.SetValueByName("huxing_wei", info.WashRoom);

            cl.SetValueByName("ceng", info.CurrentFloor);
            cl.SetValueByName("ceng_total", info.Floors);

            cl.SetValueByName("chaoxiang", GetToward(info.Toward));
            cl.SetValueByName_BigBrother("chaoxiang", GetToward_Description(info.Toward));
            cl.SetValueByName("fang_xing", GetHouseType(info.HouseType));
            cl.SetValueByName_BigBrother("fang_xing", GetHouseType_Description(info.HouseType));

            cl.SetValueByName("zhuangxiu", GetDecoration(info.Decoration));
            cl.SetValueByName_BigBrother("zhuangxiu", GetDecoration_Description(info.HouseType));


            cl.SetValueByName("pay_type_int", GetPayment(info));
            cl.SetValueByName_BigBrother("pay_type_int", GetPayment_Description(info));

            cl.SelectByName_Value("direction", GetToward(info.Toward));

            cl.SetValueByName("niandai", info.Age);
            cl.SetValueByName("area", info.Area);
            cl.SetValueByName("price", info.MonthPrice);
            cl.SetValueByID("id_description", info.Description);

            cl.SetValueByName("phone", info.Mobile);
            cl.SetValueByName("person", info.Name);

        }
        #endregion
    }
}
